package com.zb.nio.charset;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map;
import java.util.Set;

public class CharsetDemo {

    public static void main(String[] args) throws CharacterCodingException {

        // 1、获取Charset对象
        Charset charset = Charset.forName("utf8");

        // 2、建立缓冲区，准备数据
        CharBuffer buf = CharBuffer.allocate(1024);
        buf.put("测试abc");
        buf.flip();

        // 3、获取新的编码器
        CharsetEncoder charsetEncoder = charset.newEncoder();

        // 4、编码
        ByteBuffer byteBuffer = charsetEncoder.encode(buf);
        System.out.println("编码后：");
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println(byteBuffer.get());
        }

        // 5、获取新的解码器
        byteBuffer.flip();
        CharsetDecoder charsetDecoder = charset.newDecoder();
        CharBuffer decoderBuf = charsetDecoder.decode(byteBuffer);
        System.out.println("解码后：");
        System.out.println(decoderBuf);

        // 7、用其它字符格式解码
        Charset gbkChar = Charset.forName("gbk");
        byteBuffer.flip();
        System.out.println("使用其他编码进行解码：");
        System.out.println(gbkChar.decode(byteBuffer));

        // 8、获取Charset所支持的字符编码
        Map<String, Charset> scssm = Charset.availableCharsets();
        Set<Map.Entry<String, Charset>> entries = scssm.entrySet();
        for (Map.Entry<String, Charset> entry : entries) {
            System.out.println(entry + " : " + entry.getValue());
        }
    }

}
